import { t } from 'i18next'
import { UserEntity } from '@/api/create/interface'
import { SimpleUserModel, UserModel } from './interface'
import PinyinMatch from 'pinyin-match'
import { uniqBy } from 'lodash-es'

export function getItemInAll(tree: UserModel[], callback: (item: UserModel) => void | boolean) {
	let stack = [...tree]
	while (stack.length > 0) {
		const item = stack.shift()!
		const flag = callback(item)
		if (flag === false) break
		if (item.mcc.account_type === 10 && !item.attr.isSimpleCascade) {
			for (let i = item.children.length - 1; i >= 0; i--) {
				stack.unshift(item.children[i])
			}
		}
	}
}

/** 设置 often 或者 interactive 列表的搜索状态 */
export function setSearchStatusInSimple(list: SimpleUserModel[], keyword: string) {
	for (const user of list) {
		const match = keyword ? PinyinMatch.match(user.mcc.name || '', keyword) : true
		if (match === false) {
			user.status.isMatchSearch = false
		} else {
			user.status.isMatchSearch = true
		}
	}
}

/** 将 all 数据转成 often/interactive 数据 */
export const TranslatorAllToSimple = (list: UserModel[]): SimpleUserModel[] => {
	return list.map((l) => {
		return {
			mcc: l.mcc,
			status: {
				checked: false,
				isMatchSearch: true,
			},
			uuid: `${l.mcc.account_type}$$${l.mcc.account}`,
			parentId: l.parentId,
		}
	})
}

//树->平铺
export const flatAllTreeToList = (tree: UserModel[]) => {
	let stack = [...tree]
	let result = []
	while (stack.length !== 0) {
		const item = stack.shift()!
		if (item.status.isMatchSearch) {
			result.push({
				mcc: item.mcc,
				status: item.status,
				attr: item.attr,
				uuid: item.uuid,
				parentId: item.parentId,
				nestingLevel: item.nestingLevel,
			})
		}
		if (item.mcc.account_type === 10 && !item.attr.isSimpleCascade && item.status.isOpen) {
			for (let i = item.children.length - 1; i >= 0; i--) {
				let o = item.children[i]
				stack.unshift({
					mcc: o.mcc,
					status: o.status,
					attr: o.attr,
					uuid: o.uuid,
					parentId: o.parentId,
					children: o.children,
					nestingLevel: item.nestingLevel + 1,
				})
			}
		}
	}
	return result
}

interface ICascadeInAll {
	isSimpleMap: {
		[key: string]: 0 | 1 // 0:简单级联， 1：合并级联
	}
	mts: {
		[key: string]: UserEntity[]
	}
}
export const setCascadeInAll = (tree: UserModel[], { isSimpleMap, mts }: ICascadeInAll) => {
	//先处理tree顶级，编辑会议初始化进来时，tree顶级结构并没有处理好，需要兼容这个场景
	tree = tree.map((x) => {
		if (isSimpleMap[x.mcc.account] !== undefined) {
			x.attr.isSimpleCascade = isSimpleMap[x.mcc.account] === 0
		}
		return x
	})

	for (const account in mts) {
		const userList = mts[account]
		const translatorMts: UserModel[] = userList.map((x) => {
			return {
				mcc: x,
				status: {
					checked: false,
					isOpen: false,
					isMatchSearch: true,
					isOften: false,
					isInteractive: false,
				},
				attr: {
					isSimpleCascade: isSimpleMap[x.account] === 0,
					actualUuid: '',
				},
				uuid: '',
				nestingLevel: 0,
				parentId: x.parent_id || '',
				children: [],
			}
		})
		const meetingList = translatorMts.filter((x) => x.mcc.account_type === 10 && !x.attr.isSimpleCascade)

		for (let i = 0; i < meetingList.length; i++) {
			const meeting = meetingList[i]
			//合并级联
			let _arr = translatorMts.filter((x) => x.parentId === meeting.mcc.account)
			//去重
			_arr = uniqBy(_arr, (val) => `${val.mcc.account_type}$$${val.mcc.account}`)
			//排序，级联放最后
			meeting.children = [
				..._arr.filter((x) => x.mcc.account_type !== 10),
				..._arr.filter((x) => x.mcc.account_type === 10),
			]
		}
		let rootMeeting = tree.find(
			(x) => x.mcc.account_type === 10 && !x.attr.isSimpleCascade && x.mcc.account === account
		)
		if (rootMeeting) {
			let _arr = translatorMts.filter((x) => x.parentId === account)
			rootMeeting.children = [
				..._arr.filter((x) => x.mcc.account_type !== 10),
				..._arr.filter((x) => x.mcc.account_type === 10),
			]
		}
	}
	let stack = [...tree]
	while (stack.length !== 0) {
		const item = stack.pop()!
		if (item.mcc.account_type === 10 && !item.attr.isSimpleCascade) {
			for (let i = item.children.length - 1; i >= 0; i--) {
				const x = item.children[i]
				x.attr.actualUuid = `${item.attr.actualUuid}&&${x.mcc.account_type}$$${x.mcc.account}`
				x.uuid = `${x.mcc.account_type}$$${x.mcc.account}`
				if (x.mcc.account_type === 10 && !x.attr.isSimpleCascade) {
					stack.push(x)
				}
			}
		}
	}
	return tree
}

export function setSearchStatusInAll(tree: UserModel[], keyword: string) {
	let stack = [...tree],
		cash = []
	while (stack.length > 0) {
		const item = stack.pop()!
		if (item.mcc.account_type === 10 && !item.attr.isSimpleCascade) {
			item.status.isOpen = false //先全部关上
			item.status.isMatchSearch = keyword !== '' ? false : true
			for (let i = item.children.length - 1; i >= 0; i--) {
				stack.push(item.children[i])
			}
		} else {
			const match = keyword ? PinyinMatch.match(item.mcc.name || '', keyword) : true
			if (match === false) {
				item.status.isMatchSearch = false
			} else {
				item.status.isMatchSearch = true
				cash.push(item.attr.actualUuid)
			}
		}
	}
	for (const uuid of cash) {
		const UUIds = uuid.split('&&')
		if (UUIds.length > 1) {
			let cur = tree
			let parentNode = undefined
			for (let i = 0; i < UUIds.length - 1; i++) {
				parentNode = cur.find(
					(x) =>
						x.mcc.account_type === 10 &&
						!x.attr.isSimpleCascade &&
						`${x.mcc.account_type}$$${x.mcc.account}` === UUIds[i]
				)
				if (parentNode) {
					if (keyword === '') {
						parentNode.status.isOpen = false //keyword为空，代表清空搜索项，直接将级联会议不展开显示
					} else {
						parentNode.status.isOpen = true //默认展开级联会议
					}
					parentNode.status.isMatchSearch = true
					cur = parentNode.children
				}
			}
		}
	}
}

export const initUser = {
	account: '',
	account_type: 1,
	name: t('无'),
	uid: '',
}

export const getSpeakerManager = (tree: UserModel[], { superMtNum }: { superMtNum: boolean }) => {
	let flatList = [initUser]
	getItemInAll(tree, (item) => {
		//获取非外部邮箱用户，如果开启超大方会议，账号还必须是互动终端
		if (item.mcc.account_type !== 4 && (!superMtNum || (superMtNum && item.status.isInteractive))) {
			flatList.push({
				account: item.mcc.account,
				account_type: item.mcc.account_type,
				name: item.mcc.name,
				uid: `${item.parentId ? item.parentId : ''}$$${item.mcc.account_type}$$${item.mcc.account}`,
			})
		}
	})
	let list = tree
		.filter(
			//管理方只能是顶级域的非外部邮箱用户，如果开启超大方会议，账号还必须是互动终端
			(x) =>
				x.mcc.account_type !== 10 &&
				x.mcc.account_type !== 4 &&
				(!superMtNum || (superMtNum && x.status.isInteractive))
		)
		.map((item) => ({
			account: item.mcc.account,
			account_type: item.mcc.account_type,
			name: item.mcc.name,
			uid: `${item.parentId ? item.parentId : ''}$$${item.mcc.account_type}$$${item.mcc.account}`,
		}))

	return { speakerList: flatList, managerList: [initUser, ...list] }
}
